jQuery.SubmitLogin = function() {
    if( !window.location.href.match( /init$/i ) ) {
        return;
    }
    //login
    var    url = 'https://dynamic.12306.cn/otsweb/loginAction.do?method=loginAysnSuggest';
    var queryurl = "https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=init";
    //Check had login, redirect to query url
    if( window.parent && window.parent.$ ) {
        var str = window.parent.$("#username_ a").attr("href");
        if( str && str.indexOf("sysuser/user_info") != -1 ){
            window.location.href = queryurl;
            return;
        }
    }
    var count = 1;
    var timerID = 0;
    //初始化
    $("#subLink").after($("<a href='#' class='ploginButton' />")
        .attr("id", "refreshButton")
        .html("自动登录")
        .click(function() {           
            count = 1;
            $(this).html("(1)次登录中...");
            //notify('开始尝试登录，请耐心等待！', 4000);
            submitForm();
            return false;
    }));

    window.alert('如果使用自动登录功能，请输入用户名、密码及验证码后，点击自动登录，系统会尝试登录，直至成功！');

    function reLogin(){
        count ++;
        $('#refreshButton').html("("+count+")次登录中...");
        if ( count < 700)
            timerID = setTimeout(submitForm, 4000);
        else
            clearTimeout(timerID);
    }

    function subFormPlugin() {
        if($("#UserName").val()!= "" && $("#password").val() != ""
                && $("#randCode").val() != "" && $("#password").val().length > 5) {
           var form = $("#loginForm");
           if(('undefind' != $("[name='refundLoginCheck']")) && ($("[name='refundLoginCheck']").attr("checked")==true))
           {
                $("#refundLogin").val('Y');
           }
           else
           {
                $("#refundLogin").val('N');
           }	 		

           $.ajax({
               type: "POST",
               url: form.attr('action'),
               data: form.serialize(),
               timeout: 30000,
                success: function(msg){
                    if (msg.indexOf('请输入正确的验证码') > -1) {
                        alert('请输入正确的验证码！');
                        return;
                    };

                    msg = msg.replace(/\s+/, '');
                    if ( msg.indexOf('当前访问用户过多') > -1 || msg.match(/var\s+isLogin\s*=\s*false/i)) {                                        
                           reLogin();
                    }
                    else {
                        notify('登录成功，开始查询车票吧！');
                        window.location = queryurl;
                        //window.location.replace( queryurl );
                    };
                },
                error: function(msg){
                    reLogin();
                }
           })
        }
    }
    
    function submitForm(){
        var submitUrl = url;
        $.ajax({
            type: "POST",
            dataType: "json", 
            url: submitUrl,
            beforeSend: function( xhr ) {
                try{
                    xhr.setRequestHeader('X-Requested-With', {toString: function(){ return ''; }});
                    xhr.setRequestHeader('Cache-Control', 'max-age=0');
                    xhr.setRequestHeader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8');
                }catch(e){};
            },
            timeout: 20000,
            success: function(data) {
                 if(data.randError != 'Y'){
                     alert(data.randError);
                     reLogin();
                 } else {
                     $("#loginRand").val(data.loginRand);
                     subFormPlugin();
                 }
             },
            error:function(XMLHttpRequest, textStatus, errorThrown) {
                reLogin();
            }
        });
    }
}   


jQuery.SubmitOrder = function() {
	//Auto select the first user when not selected
	if( !$("input._checkbox_class:checked").length ) {
		try{
			//Will failed in IE
			$("input._checkbox_class:first").click();
		}catch(e){};
	}
	//passengerTickets
        
        
	var userInfoUrl = 'https://dynamic.12306.cn/otsweb/order/myOrderAction.do?method=queryMyOrderNotComplete&leftmenu=Y';

	var count = 1, freq = 1000, doing = false, timer, $msg = $("<div style='padding-left:470px;'></div>");
        
        //////////////////////////////////////////////
        function CheckOrderForm (formId) {
                var checkCardType = [];
                var isSelectOne = false;
                var noSelects = [];
                function toPassengerStringSplit(passenger) {
                        var pValue = passenger.passenger_name + ","
                                        + passenger.passenger_id_type_code + ","
                                        + passenger.passenger_id_no;
                        return pValue;
                };
                var ticket_type_code = {
                        student:"3",
                        child:"2",
                        adult:"1",
                        disability:"4"
                };
                var _seat_codes_resign = [];	//要改签的乘客席别
                $(".passenger_class").each(function() {
                        var id = $(this).attr("id");
                        if (this.style.display == "none") {
                                return false;
                        }
                        var value = $("#" + id + "_seat").val();
                        // 添加铺别
                        value += "," + $("#" + id + "_seat_detail").val();
                        if ($("#" + id + "_isSave")[0].checked) {
                                //不改签的不用验证"改签时，必须选择相同席别"。即同一席别的车票才能一起改签。
                                _seat_codes_resign.push( $("#" + id + "_seat").val());
                        }
                        value += "," + $("#" + id + "_ticket").val();
                        value += "," + $("#" + id + "_name").val();
                        value += "," + $("#" + id + "_cardtype").val();
                        value += "," + $("#" + id + "_cardno").val();
                        value += "," + $("#" + id + "_mobileno").val();
                        if ($("#" + id + "_isSave")[0].checked) {
                                value += "," + $("#" + id + "_isSave").val();
                                isSelectOne = true;
                        } else {
                                value += ",N";
                                noSelects.push(id + "_p");
                        }
                        if ($("#" + id + "_ticket").val() !== ticket_type_code.child) {
                                checkCardType.push({
                                        name : $("#" + id + "_name").val(),
                                        cardno : $("#" + id + "_cardno").val(),
                                        cardtype : $("#" + id + "_cardtype").val()
                                });
                        }
                        $("#" + id + "_p").val(value);
                        var passenger = $("#" + id).data("passenger");
                        if (passenger) {
                                $("#" + id + "_old").val(toPassengerStringSplit(passenger));
                        }
                });
                
                if($("#_type").val()=="resign"){
                        if(!isSupportBatchResign(_seat_codes_resign)) {
                                alert("卧铺不支持批量改签，请单张改签！");
                                return false;
                        }
                        if($.unique(_seat_codes_resign).length>1){
                                alert("改签时，必须选择相同席别");
                                return false;
                        }
                }
                var isCardSame = false;
                var cardSameName = "";	//证件号码重复的乘客姓名
                var cardSameCardNo = "";	//证件号码重复的证件号码
                $.each(checkCardType, function(index, item) {
                        if (item.cardno == "") {
                                return false;
                        }
                        $.each(checkCardType, function(index1, item1) {
                                if(item.cardtype == "1") {
                                        //一代身份证15位需要转成18位二代身份证进行验证
                                        if (index1 != index && (item1.cardtype == '1' && item1.cardno == item.cardno || item1.cardtype=='2' && item1.cardno == getCardNo18(item.cardno) )) {
                                                isCardSame = true;
                                                cardSameName = item.name;
                                                cardSameCardNo = item.cardno;
                                                return false;
                                        }
                                } else if(item.cardtype == "2") {
                                        if (index1 != index && (item1.cardtype == '1' && getCardNo18(item1).cardno == item.cardno || item1.cardtype=='2' && item1.cardno == item.cardno )) {
                                                isCardSame = true;
                                                cardSameName = item.name;
                                                cardSameCardNo = item.cardno;
                                                return false;
                                        }
                                }  else {
                                        if (index1 != index && (item1.cardtype == item.cardtype) && (item1.cardno == item.cardno)) {
                                                isCardSame = true;
                                                cardSameName = item.name;
                                                cardSameCardNo = item.cardno;
                                                return false;
                                        }
                                }
                        });
                });
                
                var id_mode = $("#orderRequest_id_mode").val();
                // 车次
                var _station_train_code = $("#_station_train_code").val();
                // 发车日期
                var _train_date_str = $("#_train_date_str").val();
                var train_date_str_year = _train_date_str.substr(0,4);
                var train_date_str_month = _train_date_str.substr(5,2);
                var train_date_str_day = _train_date_str.substr(8,2);
                //alert(isCardSame);             
                if (isCardSame && id_mode == "Y") {
                    alert("互联网售票实行实名制："+cardSameCardNo+"只能购买"+train_date_str_year+"年"+train_date_str_month+"月"+train_date_str_day+"日的"+_station_train_code+"次的一张车票！");
                    return false;
                }
                
                if ($("#_type").val() !== "") {
                    if (!isSelectOne) {
                            alert("至少选择一位乘客");
                            return false;
                    }
                }

                return true;
        }
        
	function submitForm(){
		timer = null;
                var formId = 'confirmPassenger';
                var checkRs = CheckOrderForm(formId);
                if(!checkRs) {
                    window.alert('表单检查失败!');
                    return false;
                }
		//更改提交列车日期参数
		//var wantDate = $("#startdatepicker").val();
		//$("#start_date").val(wantDate);
		//$("#_train_date_str").val(wantDate);
                var syncUrl = 'confirmPassengerAction.do?method=confirmSingleForQueueOrder';
                $("#" + formId).ajaxSubmit({
                        url : syncUrl,
                        type : "POST",
                        dataType: "json",
                        success:function(data){
                                if(data.errMsg != 'Y'){                                        
                                    var errMsg = data.errMsg;
                                    if ( errMsg.indexOf('验证码不正确') > -1 )
                                    {
                                        window.alert(data.errMsg);
                                        return false;
                                    }
                                    else if ( errMsg.indexOf('重复提交') > -1 )
                                    {
                                        window.location.reload(true);
                                        return false;
                                    }
                                    else
                                    {
                                        reSubmitForm('msg:' + errMsg);
                                    }

                                } else {
                                        //timer = new OrderQueueWaitTime(tourFlag,waitFunc,finishFun);
                                        //timer.start();
                                }
                        },
                        error:function(XMLHttpRequest, textStatus, errorThrown) {
                                reSubmitForm("下单失败！网络忙,重试中。。。");
                        }                    
                });
                
	};
	function reSubmitForm(msg){
		if( !doing )return;
		count ++;
		$msg.html("("+count+")次自动提交中... " + (msg || ""));
		timer = setTimeout( submitForm, freq || 50 );
	}
        
	function stop ( msg ) {
		doing = false;
		$msg.html("("+count+")次 已停止");
		$('#refreshButton').html("自动提交订单");
		timer && clearTimeout( timer );
		msg && alert( msg );
	}
	function reloadSeat(){
		$("select[name$='_seat']").html('<option value="M" selected="">一等座</option><option value="O" selected="">二等座</option><option value="1">硬座</option><option value="3">硬卧</option><option value="4">软卧</option>');
	}
	//初始化

	if($("#refreshButton").size()<1){

		//	//重置后加载所有席别
		//	$("select[name$='_seat']").each(function(){this.blur(function(){
		//		alert(this.attr("id") + "blur");
		//	})});
		////初始化所有席别
		//$(".qr_box :checkbox[name^='checkbox']").each(function(){$(this).click(reloadSeat)});
		//reloadSeat();

		//日期可选
		$("td.bluetext:first").html('<input type="text" name="orderRequest.train_date" value="' +$("#start_date").val()+'" id="startdatepicker" style="width: 150px;" class="input_20txt"  onfocus="WdatePicker({firstDayOfWeek:1})" />');
		$("#start_date").remove();
		 
		$(".tj_btn").append($("<a style='padding: 5px 10px; background: #2CC03E;border-color: #259A33;border-right-color: #2CC03E;border-bottom-color:#2CC03E;color: white;border-radius: 5px;text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.2);'></a>").attr("id", "refreshButton").html("自动提交订单").click(function() {
			//alert('开始自动提交订单，请点确定后耐心等待！');
			if( this.innerHTML.indexOf("自动提交订单") == -1 ){
				//doing
				stop();
			} else {
				if( window.submit_form_check && !window.submit_form_check("confirmPassenger") ) {
					return;
				}
				count = 0;
				doing = true;
				this.innerHTML = "停止自动提交";
				reSubmitForm();
			}
			return false;
		}));
		$(".tj_btn").append("自动提交频率：")
			.append($("<select id='freq'><option value='50' >频繁</option><option value='500' selected='' >正常</option><option value='2000' >缓慢</option></select>").change(function() {
				freq = parseInt( $(this).val() );
			}))
			.append($msg);
		//alert('如果使用自动提交订单功能，请在确认订单正确无误后，再点击自动提交按钮！');
		
		//铁道路修改验证码规则后 优化 by 冯岩
		$("#rand").bind('keydown', function (e) {
			var key = e.which;
			if (key == 13) {
				$("#refreshButton").click();
			}
		});
	}
};